<script setup lang="ts">
import Item from "@/layouts/components/HeadMenu/item.vue";
import {getParents} from "@/utils/tree";

interface MenuProps {
  selectedKey: string;
  menus: any[];
  theme: string;
  inverted: boolean;
}

const emits = defineEmits(['changeSelectedKey'])
const props = withDefaults(defineProps<MenuProps>(), {
  theme: "dark",
  inverted: true
});


const selectKey = defineModel({
  type: String,
  default: '',

})
const handleMenu = (menu: any) => {
  if (menu.children) {
    return
  }
  selectKey.value = menu.id
  emits('changeSelectedKey', selectKey.value)
}
const parentsNodes = computed(() => {
  const data = getParents(props.menus, selectKey.value)
  if (!data) {
    return []
  }
  return data.map((node: any) => node.id)
})
provide(/* 注入名 */ 'headMenu', /* 值 */ reactive({
  selectKey,
  handleMenu,
  parentsNodes
}))

const topKey = computed(() => {
  const parents = parentsNodes.value;
  if (!parents) {
    return "";
  }
  return parents.pop()
})
</script>

<template>
  <ul class=" j-head-menu" :class="theme">
    <template v-for="(menu, index) in menus" :key="index">
      <lay-dropdown :disabled="!menu.children">
        <li :class="{'lay-this': menu.id===topKey,'inverted':inverted}" @click="handleMenu(menu)">
          <j-icon :name="menu.icon"></j-icon>
          <div>{{ menu.title }}</div>
        </li>
        <template #content>
          <lay-dropdown-menu trigger="click">
            <Item :menus="menu.children"></Item>
          </lay-dropdown-menu>
        </template>
      </lay-dropdown>

    </template>

  </ul>
</template>

<style lang="less" scoped>
.j-head-menu {
  display: flex;
  padding: 0 12px;
  height: 50px;

  &.light {
    li:hover {
      background: whitesmoke;
      color: var(--global-primary-color);
    }
  }

  &.dark {
    li:hover {
      background: rgba(0, 0, 0, 1);
      color: var(--global-primary-color);
    }
  }

  li {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 3px;
    padding: 0 8px;
    cursor: pointer;
  }

  .lay-this:not(.inverted) {
    background: var(--global-primary-color) !important;
    color: #fff !important;
  }

  .lay-this.inverted {
    position: relative;
    color: var(--global-primary-color) !important;

    &::after {
      position: absolute;
      bottom: 2px;
      content: " ";
      width: 100%;
      border-bottom: 2px solid var(--global-primary-color);
    }
  }
}
</style>
